package cn.bdqn.web;

import cn.bdqn.entity.Air;
import cn.bdqn.service.AirService;
import cn.bdqn.service.impl.AirServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@WebServlet(value = "/air/doAdd")
public class AirDoAddServlet extends HttpServlet {
    /*
    3. 执行添加空气质量信息
    路径.
        POST	http://localhost/air/doAdd
    参数.
        districtId = integer
        monitorTime = date
        pm10 = integer
        pm25 = integer
        monitoringStation = string
        (均为必传项)
    响应.
        1. 将数据保存到数据库.
        2. 重定向到首页.
     */

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //0. 处理post请求乱码
        req.setCharacterEncoding("UTF-8");
        //1. 接收全部参数(返回的Map是一个带锁的map,不允许删除)
        Map<String, String[]> params = req.getParameterMap();






        //2. 封装数据.
        //2.1 将时间类型手动转换.
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String monitorTimeStr = params.get("monitorTime")[0];
        Date monitorTime = null;
        try {
            monitorTime = sdf.parse(monitorTimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //2.2.1 将map中的时间monitorTime干掉,避免报错
        //2.2.2 默认的map是带锁.
        Map<String,String[]> map = new HashMap<>();
        map.putAll(params);
        map.remove("monitorTime");
        //2.3 将数据封装到Air对象中.


        Air air = new Air();
        air.setMonitorTime(monitorTime);
        try {
            BeanUtils.copyProperties(air,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //--------------------------------------
        //3. 调用service保存数据.
        AirService airService = new AirServiceImpl();
        airService.save(air);
        //4. 重定向到首页.
        resp.sendRedirect(req.getContextPath() + "/index");
    }
}
